package cluster

import (
	"gitee.com/cooge/impush/cluster/conn"
	"gitee.com/cooge/impush/core"
	"gitee.com/cooge/impush/message"
	"gitee.com/cooge/impush/user"
	"github.com/sirupsen/logrus"
	"runtime"
	"time"
)


func addHandlerFunc(userid string,value user.UserConn) {
	if value.IsLocal() {
		sendAddUser(userid)
	} else {
		logrus.Debug("集群用户，不向其它机器发送", userid)
	}
}
func deleteHandlerFunc(userid string, value user.UserConn, ti *time.Time) {
	if value.IsLocal()  {
		sendDeleteUser(userid, ti)
	} else {
		logrus.Debug("集群用户，不向其它机器发送", userid)

	}
}
func initUserFilter() {
	userFilter := core.NewFilterHandlerFunc(addHandlerFunc, deleteHandlerFunc)
	core.AddFilter(userFilter)
}



type ClusterConnUser struct {
	*user.UserLite
}

func NewClusterConnUser(conn user.UserTCPConn, livetime int, clusterUser *clusterUser) *ClusterConnUser {
	tt, err := time.Parse(timeLayout, clusterUser.Time)
	if err == nil {
		return &ClusterConnUser{UserLite: &user.UserLite{UserTCPConn: conn, LiveTime: livetime, UserId: clusterUser.UserId, CreateTime: &tt,Type:message.FULL_CLUSTER,Local:false}}
	}
	return nil

}
func (ccu *ClusterConnUser) Close(userId string) error {
	core.DeleteUser(userId, ccu)
	return nil
}
func (ccu *ClusterConnUser) SendMessage(msg *message.Message) (int, error) {
	bs := msg.MessageToByte()
	return ccu.Write(bs)
}

func addClusterUser(userid string, cu *ClusterConnUser) {
	logrus.Debug("添加集群用户", userid, cu)
	cs := core.GetUser(userid)
	if cs != nil {
		us:=cs.GetAllArray()
		core.AddUser(userid, cu)
		for _, v := range us {
			if !v.IsLocal() {
				u, ok := v.(*ClusterConnUser)
				if ok {
					if cu.UserTCPConn == u.UserTCPConn {
						if u.CreateTime.Equal(*cu.CreateTime) || u.CreateTime.Before(*cu.CreateTime) {
							core.DeleteUser(userid, u)
						}
					}
				}
			}
		}
	}

}

func deleteClusterUser(userid string, cu *ClusterConnUser) {
	logrus.Debug("删除集群用户", userid, cu)
	cs := core.GetUser(userid)
	if cs != nil {
		for _, v := range cs.GetAllArray() {
			if !v.IsLocal() {
				u, ok := v.(*ClusterConnUser)
				if ok {
					if cu.UserTCPConn == u.UserTCPConn {
						if u.CreateTime.Equal(*cu.CreateTime) || u.CreateTime.Before(*cu.CreateTime) {
							core.DeleteUser(userid, u)
						}
					}
				}
			}
		}
	}
}

func deleteClusterConnUser(cu *conn.ClusterConn) {

	for num, userid := range core.GetALLUsers() {
		cs := core.GetUser(userid)
		if cs != nil {
			for _, v := range cs.GetAllArray() {
				if !v.IsLocal() {
					u, ok := v.(*ClusterConnUser)
					if ok {
						if cu.UserTCPConn == u.UserTCPConn {
							core.DeleteUser(userid, u)
						}
					}
				}
			}
		}
		if num>>7<<7 == num {
			runtime.Gosched()
		}
	}
}